import {Component, Inject, Injectable, OnInit, ViewChild} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {DictItemModule, DictModule} from '../../../service/dict';
import {Router} from '@angular/router';
import {UtilityService} from '../../../service/utils.service';
import {MenuItem, TreeNode} from 'primeng/api';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {appConfig} from '../../../service/common';
import {CommondictServe} from '../../../service/commonDict';

@Component({
    selector: 'app-dict',
    templateUrl: './dict.component.html',
    styleUrls: ['./dict.component.less']
})

// 依赖注入，把url链接注入进来即可
@Injectable()
export class DictComponent  implements  OnInit  {
    private msg: any;
    constructor(
        private http: _HttpClient,
        private router: Router,
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService,
        private commondict: CommondictServe
    ) {
    }
    dict: DictModule = new DictModule(); // 绑定数据
    dictAdd: DictModule = new DictModule(); // 绑定新增数据
    dictItemAdd: DictItemModule = new DictItemModule(); // 绑定业务字典项数据
    treeshow = false; // 是否显示树结构
    isEdit = false; // 默认是新增
    // guidParents 父字典
    guidParents: any;
    modalVisible = false; // 弹出框是否打开
    dictionaryItems = false; // 新增字典项是否打开
    creatExit = false; // 默认是新增
    eventData: any;
    dictInfo: any; // 业务字典数据信息
    data: any[] = []; // 表格数据
    isappcodeSlash = false; // 验证是否重复
    expandForm = false;
    treedata: any[]; // tree组件数据
    treemenus: MenuItem[];
    searchTitle: string;
    // 翻页和总数数据
    page: any;
    total: number;
    loading = false;
    treeSelectData: any; // 树节点选择的数据
    nodrop: boolean; // 是否有拖动的树
    sysEdit = false; // 系统级的不允许修改，默认都可以修改
    sysEditItem = false; // 系统级的字典项不允许修改，默认都可以修改
    dictTitle: string; // 业务字典弹框标题
    dictItemTitle: string; // 业务字典弹框标题
    isParent: boolean; // 是否有父字典
    // fromType 字典项来源类型
    fromType: any;
    // itemType  字典项类型
    itemType = [
        { text: '来自业务字典', value: false, key: 'dict' },
        { text: '实际值', value: false, key: 'value' }
    ];
    selectedRows: any; // 选择的总数
    // dictType 业务字典类型
    dictType: any;
    // 字典项
    itemValues: any;
    // 实际值
    itemSendvalue: any;
    // 表头按钮
    buttons = [
        {key: 'add', value: '新增业务字典', buttonCode: appConfig.funcObject.dict.addDict}
    ]
    // 筛选条件
    conditions = [
        { text: '所有业务字典', value: false, key: 'all' },
        { text: '跟字典', value: false,  key: 'root' },
    ]
    defaultValue: string; // 业务字典实际值
    dictGuid: string;
    headerData = [  // 配置表头内容
        {value: '业务字典', key: 'dictKey',  isclick: false},
        {value: '字典名称' , key: 'dictName', isclick: false},
        {value: '字典类型', key: 'dictType',  isclick:  false},
        {value: '字典项来源' , key: 'fromType', isclick: false}
    ];
    moreData = { morebutton: true,
        buttons: [
            {key: 'Overview' , value: '查看概况'},
            {key: 'Authority' , value: '权限配置'}
        ]
    }
    pageIndex = 1; // 当前页数
    // 右击菜单数据
    configTitle: any;
    selectionType: string; // 树类型
    isCancel: boolean; // 是否是取消
    ngOnInit() {
        this.getData(); // 只会触发一次，但是ngchanges并不会触发咋办
        this.nodrop = true;
        this.selectionType = 'single';
        this.configTitle = {value: '修改', buttonCode: appConfig.funcObject.dict.editDict}
        this.dictQueryKey()
    }

    // 根据key查询业务字典
    dictQueryKey() {
        this.commondict.queryDictKey(appConfig.dictKeyList.dictType)
            .subscribe((val) => {
                this.dictType = val.result;
            })

        this.commondict.queryDictKey(appConfig.dictKeyList.dictfromType)
            .subscribe((val) => {
                this.fromType = val.result;
            })
    }

    getData(options?) {
        if (options) {
            this.pageIndex = 1;
        }
        this.page = {
            condition: this.objJson,
            page: {
                current: this.pageIndex,
                size: this.dict.size,
                orderByField: 'guid', // 排序接口
                asc: false // asc 默认是true  升序排序，时间类型 用false， 降序
            }
        };

        // 调用服务来获取列表节点操作
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.sysDictList ,  this.page)
            .subscribe(
                (val) => {
                    for (let i = 0; i < val.result.records.length; i++) {
                        if (val.result.records[i].dictType === '应用级') {
                            val.result.records[i].buttonData = [{key: 'dels', value: '删除', buttonCode: appConfig.funcObject.dict.delDict}, {key: 'lookDicttree', value: '查看', buttonCode:appConfig.funcObject.dict.DictItem}];
                        } else {
                            val.result.records[i].buttonData = [ {key: 'lookDicttree', value: '查看', buttonCode:appConfig.funcObject.dict.DictItem}];
                        }
                        val.result.records[i].isAcitve = false; // 默认为false， 不显示颜色
                    }
                    this.data = val.result.records; // 绑定列表数据
                    this.total = val.result.total;
                    sessionStorage.setItem('sysdata', JSON.stringify(val.result.records));
                });

    }


    // 请求父业务字典
    getDict() {
        this.page = {
            page: {
                current: 1,
                size: 10000, // 先写死长度
            }
        };
        // 调用服务来获取列表节点操作
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.sysDictList ,  this.page)
            .subscribe(
                (val) => {
                    this.guidParents = val.result.records;
                });
    }

    // 枚举值转换
    dictTypeMode(event) {
        if (event.dictType === '应用级') {
            event.dictType = 'a';
        } else if (event.dictType === '系统级') {
            event.dictType = 's';
        }
    }

    formTypeMode(event) {
        if (event.fromType === '字典项') {
            event.fromType = '0';
        } else if (event.fromType === '单表') {
            event.fromType = '1';
        } else if (event.fromType === '多表或视图') {
            event.fromType = '2';
        }
    }



    // 列表组件传过来的内容
    addHandler(event) {
        this.isCancel = true; // 进入是新增/或者修改
        this.isParent = false;
        this.isappcodeSlash = false;
        this.getDict();
        if (event === 'add') {
            for (const key in this.dictAdd) {
                delete this.dictAdd[key];
            }
            this.dictAdd.fromType = '0'; // 弹出框默认选中
            this.sysEdit = false; // 允许修改
            this.dictTitle = '新增业务字典'
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.creatExit = true;
        } else { // 代表修改，把修改的内容传递进去，重新渲染
            if (event.guidParents !== '') { // 代表父组件，那么就选中父组件swatch
                this.isParent  = true;
            }
            this.dictAdd =  event;
            this.eventData = event;
            this.dictTypeMode(event); // 枚举值转换
            this.formTypeMode(event); // 枚举值转换
            this.dictTitle = '修改业务字典'
            if (event.dictType === 'a') {
                this.sysEdit = false; // 允许修改
            } else {
                this.sysEdit = true; // 系统级不允许修改
            }
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.creatExit = false;
        }
    }


    // 验证是否重复
    AppCodeexit(appType, appCode) {
        if(appType === '新增业务字典') {
            let objJson = {
                guid: '',
                dictKey: appCode
            }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.existAddDictKey , objJson)
                .subscribe(
                    (sus) => {
                        if (sus.result) {
                            this.isappcodeSlash = true; // 重复
                        } else {
                            this.isappcodeSlash = false; // 不重复
                        }
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        } else {
            let objJson = {
                guid: this.dictAdd.guid,
                dictKey: appCode
            }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.existUpdateDictKey , objJson)
                .subscribe(
                    (sus) => {
                        if (sus.result) {
                            this.isappcodeSlash = true; // 重复
                        } else {
                            this.isappcodeSlash = false; // 不重复
                        }
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        }
    }



    // 列表传入的翻页数据
    monitorHandler(event) {
        this.pageIndex = event;
        this.getData();
    }


    buttonEvent(e) {
        if (e.names) {
            if (e.names.key === 'dels') {
               this.deleatData(e);
            } else { // 查看
                this.dictGuid = e.guid;
                for (let i = 0; i <  this.data.length; i ++) {
                    if (e.guid === this.data[i].guid) {
                        this.data[i].isAcitve = true;
                    } else {
                        this.data[i].isAcitve = false;
                    }
                }
                // 请求树接口
                this.defaultValue = e.defaultValue.substring(e.defaultValue.indexOf('.') + 1, e.defaultValue.length);
                if (e.fromType === '字典项') { // 调用一次性查询接口
                    this.queryAllTreeList(e.guid);
                } else {
                    this.getTreeList(e.guid);
                }

                this.dictInfo = e; // 当前选中的业务字典，绑定 全局使用，用来重新查询树
            }
        }
    }


    // 接受子组件删除的数据 单条还是多条
    deleatData(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除所选数据?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.sysDictDel + '/' + event.guid)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            if ( !(( this.total - 1) % 10)) {
                                // if ( !(( this.total - this.acfundata.length) % 10)) { // 支持批量删除的方法
                                this.dict.pi -- ;
                                this.getData();
                            }
                            this.getData();
                        });
            },
            onCancel: () => {
                console.log('取消成功');
            }
        });
    }


    // 列表按钮方法
    buttonDataHandler(event) {
        console.log(event); // 根据event.value来判断不同的请求，来获取结果和方法或者进行路由的跳转
        if (event.value ===  'Authority') {
            console.log(event.key);
        }

        if (event.value ===  'Overview') {
            console.log(event.key);
        }

    }



    // 处理行为代码，跳转、弹出框、其他交互
    isActive(event) {
        console.log(event); // 拿到数据进行判断，是跳转路由还是弹出框弹出
    }

    // 查询树方法
    getTreeList(event) {
        this.utilityService.postData(appConfig.serverUrl  + appConfig.API.sysDictsTree + '/' + event, {})
            .subscribe(
                (val) => {
                    if (val.result.dictName) {
                        val.result.label = val.result.dictKey + ':' + val.result.dictName;
                        val.result.defaultValue = this.defaultValue;
                        val.result.expandedIcon = 'fa-folder-open';
                        val.result.collapsedIcon = 'fa-folder';
                        val.result.childDict = true; // 是业务字典
                    }
                    if (val.result.children) {
                        for (let i = 0 ; i < val.result.children.length; i++) {
                            if (val.result.children[i].dictName) { // 子业务字典
                                val.result.children[i].label = val.result.children[i].dictKey + ':' + val.result.children[i].dictName;
                                val.result.children[i].expandedIcon = 'fa-folder-open';
                                val.result.children[i].collapsedIcon = 'fa-folder';
                                val.result.children[i].childDict = true;
                                val.result.children[i].children = [{'label': ''}];
                            }
                            if (val.result.children[i].itemName) { // 字典项
                                // 判断默认值
                                if (val.result.children[i].itemValue === this.defaultValue) {
                                    val.result.children[i].icon = 'anticon anticon-tag';
                                } else {
                                    val.result.children[i].icon = 'fa-file-word-o';
                                }
                                val.result.children[i].label = val.result.children[i].itemValue + '---' + val.result.children[i].itemName;
                                val.result.children[i].childDict = false;
                            }
                        }
                    }
                    const treeData = [];
                    treeData.push(val.result);
                    this.treedata  = treeData;
                    this.treeshow = true;
                    // 展开所有的
                    this.treedata.forEach( node => {
                        this.expandRecursive(node, true);
                    } );
                },
            );
    }

    // 下拉查询树节点方法
    getTreeNode(event) {
        this.utilityService.postData(appConfig.serverUrl  + appConfig.API.sysDictsTree + '/' + event.guid, {})
            .subscribe(
                (val) => {
                    this.treeResult = event.guid; // 赋值
                    event.children = val.result.children;
                    // 组装树
                    if (val.result.dictName) {
                        val.result.label = val.result.dictName;
                        val.result.expandedIcon = 'fa-folder-open';
                        val.result.collapsedIcon = 'fa-folder';
                        val.result.childDict = true; // 是业务字典
                    }
                    if (val.result.children) {
                        for (let i = 0 ; i < val.result.children.length; i++) {
                            if (val.result.children[i].dictName) { // 子业务字典
                                val.result.children[i].label = val.result.children[i].dictName;
                                val.result.children[i].expandedIcon = 'fa-folder-open';
                                val.result.children[i].collapsedIcon = 'fa-folder';
                                val.result.children[i].childDict = true;
                                val.result.children[i].children = [{'label': ''}];
                            }
                            if (val.result.children[i].itemName) { // 字典项
                                // 判断默认值
                                if (val.result.children[i].itemValue === this.defaultValue) {
                                    val.result.children[i].icon = 'anticon anticon-tag';
                                } else {
                                    val.result.children[i].icon = 'fa-file-word-o';
                                }
                                val.result.children[i].label = val.result.children[i].itemValue + '---' + val.result.children[i].itemName;
                                val.result.children[i].childDict = false;
                            }
                        }
                    }

                },
            );
    }

    //  一次性查询所有的接口
    queryAllTreeList(event) {
        this.utilityService.postData(appConfig.serverUrl  + appConfig.API.sysDictsTree + '/' + event, {})
            .subscribe(
                (val) => {
                    if (val.code === '200' || val.code === 200) {
                        if (val.result.children !== undefined && val.result.children.length > 0) {
                            val.result.label = val.result.dictKey + ':' + val.result.dictName;
                            val.result.defaultValue = this.defaultValue;
                            val.result.expandedIcon = 'fa-folder-open';
                            val.result.collapsedIcon = 'fa-folder';
                            val.result.childDict = true; // 是业务字典
                            this.treedata = [val.result];
                            this.iteration(this.treedata); // 递归更改树节点信息
                        } else {
                            val.result.label = val.result.dictKey + ':' + val.result.dictName;
                            val.result.defaultValue = this.defaultValue;

                            val.result.expandedIcon = 'fa-folder-open';
                            val.result.collapsedIcon = 'fa-folder';
                            val.result.childDict = true; // 是业务字典
                            this.treedata = [val.result];
                        }
                        this.treeshow = true; // 显示树结构
                        this.treedata.forEach( node => {
                            this.expandRecursive(node, true);
                        });
                    }
                    this.treeshow = true;
                },
            );
    }



    // 递归拼接树结构
    iteration(node) {
        for (let i = 0; i < node.length; i++) {
            if (node[i].children !== undefined && node[i].children.length > 0) {
                node[i].label =  node[i].dictKey + ':' + node[i].dictName;
                node[i].expandedIcon = 'fa-folder-open';
                node[i].collapsedIcon = 'fa-folder';
                node[i].childDict = true; // 是业务字典
                this.iteration(node[i].children); // 继续调用
            } else { // 字典项
                node[i].label = node[i].dictKey + '---' + node[i].dictName;
                if (node[i].dictKey === this.defaultValue) {
                    node[i].icon = 'anticon anticon-tag';
                } else {
                    node[i].icon = 'fa-file-word-o';
                }
                node[i].childDict  =  false; // 不是业务字典，是字典项目
            }
        }
    }



    selectedRow(event) {
        // 选中方法，折叠层按钮显示方法
        if (event.selectedRows.length === 1) {
            // 请求树接口
            // this.getTreeList(event.selectedRows[0].guid);
        } else {
            // this.treeshow = false;
        }
    }

    treeResult: string; // 接收ID值
    istrue: boolean; // 树请求标识符 true才可以请求
    // 展开节点事件
    Unfold(event) {
        if (event.node.guid === this.treeResult) {
            this.istrue = false;
        } else {
            this.istrue = true;
        }
        if (this.istrue) { // 为true的时候 说明不存在，没有请求过 才去请求
            // this.getTreeNode(event.node);
        }
    }

    objJson = {};
    // 搜索框
    search() {
        this.treeshow = false;
        this.objJson = this.dict;
        this.getData(this.objJson)
    }

    reset() {
            this.dict = new DictModule();
            this.objJson = this.dict;
            this.getData(this.objJson)
        }
    // 弹出框保存组件
    save() {
        console.log(this.isCancel)
        if(this.isCancel) { // false代表是取消，不进入新增。修改方法
            const jsonOption = this.dictAdd;
            if (this.creatExit) { // 调用新增的逻辑
                // 调用服务来获取列表节点操作
                this.utilityService.postData(appConfig.serverUrl  + appConfig.API.sysDictAdd, jsonOption)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            this.getData();
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                            this.getData();
                        }
                    );

            } else { // 调用修改的逻辑
                this.utilityService.putData(appConfig.serverUrl + appConfig.API.sysDictEdit, jsonOption)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            this.getData();
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                            this.getData();
                        });
            }
            this.modalVisible = false;
            this.treeshow = false; // 关闭右侧树结构
        }
    }

    // 取消
    cancel() {
        this.data = JSON.parse(sessionStorage.getItem('sysdata'));
        this.modalVisible = false;
        this.isCancel = false;
    }

    // 树的方法
    // 右击菜单传递值
    RightSelect(event) {
        this.treeSelectData = event.node; // 右击选中的数据绑定全局使用
        console.log(this.treeSelectData)
        if (this.treeSelectData.childDict) { // 代表是业务字典
            if (this.dictInfo.dictType === '系统级') {
                if(this.dictInfo.fromType === '字典项') { // 系统级 字典项，业务字典菜单允许新增业务字典，允许修改业务字典, 不允许删除
                    this.treemenus = [
                        {label: '修改业务字典', icon: 'anticon anticon-edit' , id: appConfig.funcObject.dict.editDict, command: (event) => this.exitdict('S')},
                        {label: '新增字典项', icon: 'anticon anticon-plus-square-o' , id: appConfig.funcObject.dict.adddictItem, command: (event) => this.addDictItem()},
                    ];
                } else { // 代表是视图或者单表, 只允许修改业务字典
                    this.treemenus = [
                        {label: '修改业务字典', icon: 'anticon anticon-edit' , id: appConfig.funcObject.dict.editDict, command: (event) => this.exitdict('S')}
                    ];
                }
            } else { // 代表应用级
                if(this.dictInfo.fromType === '字典项') { // 应用级 字典项，删除 修改 增加字典项都可以
                    this.treemenus = [
                        {label: '修改业务字典', icon: 'anticon anticon-edit' , id: appConfig.funcObject.dict.editDict, command: (event) => this.exitdict('A')},
                        {label: '新增字典项', icon: 'anticon anticon-plus-square-o' , id: appConfig.funcObject.dict.adddictItem,command: (event) => this.addDictItem()},
                        {label: '删除业务字典', icon: 'anticon anticon-minus-square-o',id: appConfig.funcObject.dict.delDict, command: (event) => this.delectDict()},

                    ];
                } else { // 代表是应用级的视图或者单表, 允许修改和删除, 不允许修改
                    this.treemenus = [
                        {label: '修改业务字典', icon: 'anticon anticon-edit' , id: appConfig.funcObject.dict.editDict, command: (event) => this.exitdict('A')},
                        {label: '删除业务字典', icon: 'anticon anticon-minus-square-o', id: appConfig.funcObject.dict.delDict,command: (event) => this.delectDict()},

                    ];
                }
            }
            } else {
           // 代表不是业务字典，是字典项
            // 根据字典项父级的系统级和字典项来判断，这里写好先注释，等后台接口
            if (this.treeSelectData.parentDictType === '系统级' || this.treeSelectData.dictType === '系统级') {
                if(this.treeSelectData.parentFromType === '字典项' || this.treeSelectData.fromType === '字典项') { // 系统级和来自字典项， 那么对应的字典项， 允许修改，但是不允许修改key和name，明天判断一下
                    this.treemenus = [
                        {label: '修改字典项', icon: 'anticon anticon-edit' , id: appConfig.funcObject.dict.editdictItem,command: (event) => this.exitdictItem('S')},
                        {label: '设置默认值', icon: 'anticon anticon-tag' , id: appConfig.funcObject.dict.setValue,command: (event) => this.setdefault()},
                    ];
                } else { // 系统级来自单表，菜单为空
                    this.treemenus = [
                        {label: '暂无更多操作', icon: 'anticon anticon-exclamation'},
                    ];
                }

            } else { // 代表应用级
                if(this.treeSelectData.parentFromType === '字典项' || this.treeSelectData.fromType === '字典项') { // 系统级和来自字典项， 那么对应的字典项， 允许修改，但是不允许修改key和name
                    this.treemenus = [
                        {label: '修改字典项', icon: 'anticon anticon-edit' , id: appConfig.funcObject.dict.editdictItem, command: (event) => this.exitdictItem('A')},
                        {label: '删除字典项', icon: 'anticon anticon-minus-square-o' , id: appConfig.funcObject.dict.deldictItem, command: (event) => this.delectdictItem()},
                        {label: '设置默认值', icon: 'anticon anticon-tag' , id: appConfig.funcObject.dict.setValue, command: (event) => this.setdefault()},
                    ];
                } else { // 应用级的来自单表，菜单为空,任何操作都没有
                    this.treemenus = [
                        {label: '暂无更多操作', icon: 'anticon anticon-exclamation'},
                    ];
                }
            }

        }
    }

    // 左击树菜单节点信息
    TreeSelect(event) {

    }


    // 删除业务字典
    delectDict() {
        this.modal.open({
            title: '是否删除',
            content: '您确认要删除选中的业务字典吗？删除业务字典对应的字典项也会删除',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.sysDictDel + '/' +  this.treeSelectData.guid)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            if ( !(( this.total - 1) % 10)) {
                                // if ( !(( this.total - this.acfundata.length) % 10)) { // 支持批量删除的方法
                                this.dict.pi -- ;
                                this.getData();
                            }
                            this.getData();
                            this.getTreeList(this.dictInfo.guid);
                        });
            },
            onCancel: () => {
                console.log('失败');
            }
        });
    }

    // 批量删除业务字典
    deleteBatch(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除这' + event.length + '条业务字典吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let delarray = [];
                for( let i = 0; i < event.length; i++) {
                    delarray.push(event[i].guid);
                }
                let deletaObj = {
                    deleteList: delarray
                }
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.deleteSysDictList, deletaObj )
                    .subscribe(
                        (val) => {
                            this.getData();
                            this.selectedRows = []
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (error) => {
                            this.selectedRows = []
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.selectedRows = [];
                this.getData();
            }
        });
    }

    // 删除业务字典项
    delectdictItem() {
        this.modal.open({
            title: '是否删除',
            content: '您确认要删除选中的字典项吗',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.sysDicttems + '/' +  this.treeSelectData.guid)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            if(this.treeSelectData.fromType === '字典项') {
                                this.queryAllTreeList(this.dictInfo.guid)
                            } else {
                                this.getTreeList(this.dictInfo.guid);
                            }
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                            if(this.treeSelectData.fromType === '字典项') {
                                this.queryAllTreeList(this.dictInfo.guid)
                            } else {
                                this.getTreeList(this.dictInfo.guid);
                            }
                        });
            },
            onCancel: () => {
                console.log('失败');
            }
        });
    }

    // 选择字典项为业务字典时的改变
    itemTypeChange(type) {
        // 字典项类型
        if(type === 'dict') { // 代表业务字典，调用接口
            this.utilityService.getData(appConfig.serverUrl  + appConfig.API.queryDictExcept + '/' + this.treeSelectData.guid)
                .subscribe(
                    (val) => {
                        this.itemValues = val.result;
                    });
        }
    }
    // 根据guid查询业务字典项
    itemValueChange(dictGuid) {
        if(dictGuid) { // 代表业务字典，调用接口
            this.utilityService.getData(appConfig.serverUrl  + appConfig.API.queryListByDictId + '/' + dictGuid)
                .subscribe(
                    (val) => {
                        this.itemSendvalue = val.result;
                    });
        }
    }
    // 新增字典项
    addDictItem() {
        this.sysEditItem = false; // 允许新增
        this.dictItemAdd = new DictItemModule(); // 初始化模块
        this.isEdit  = false; // 新增
        this.isCancel = true; // 进入是新增/或者修改
        this.dictItemTitle = '新增字典项'
        this.dictItemAdd.itemType = 'value'; // 默认字典值
        this.dictionaryItems = true; // 打开弹出框
    }

    // 修改字典项
    exitdictItem(option?) {
        if(option && option === 'S') { // 系统级的字典项，不允许修改itemValue
            this.sysEditItem = true;
        } else {
            this.sysEditItem = false;
        }
        this.isEdit  = true; // 修改
        this.utilityService.getData(appConfig.serverUrl  + appConfig.API.sysDictItems + '/' + this.treeSelectData.guid)
            .subscribe(
                (val) => {
                    this.dictItemAdd =  val.result;
                });
        this.isCancel = true; // 进入是新增/或者修改
        this.dictItemTitle = '修改业务字典项'
        this.dictionaryItems = true; // 打开弹出框
    }


    // 修改业务字典
    exitdict(option?) {
        if(option && option ===  'S') { // 代表是系统级
            this.sysEdit = true; // 不允许修改
        } else {
            this.sysEdit = false; // 允许修改
        }
        // 根据guid查询业务字典详情，然后去复制修改信息
        this.utilityService.getData(appConfig.serverUrl  + appConfig.API.sysDictAdd + '/' + this.treeSelectData.guid)
            .subscribe(
                (val) => {
                    this.dictAdd =  val.result;
                    this.dictTypeMode(val.result); // 枚举值转换
                    this.formTypeMode(val.result); // 枚举值转换
                });
        this.isCancel = true;
        this.modalVisible = true;
    }

    // 设置默认值
    setdefault() {
        this.modal.open({
            title: '是否确定',
            content: '是否确定设置' + this.treeSelectData.itemName + '为' + this.treeSelectData.parent.dictName + '业务字典默认值?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let jsonObj = {
                    guid: this.treeSelectData.parent.guid,
                    sysDictItemGuid: this.treeSelectData.guid
                }
                this.utilityService.putData(appConfig.serverUrl + appConfig.API.setDefaultValue, jsonObj)
                    .subscribe(
                        (val) => {
                            this.defaultValue = val.result.defaultValue.substring(val.result.defaultValue.indexOf('.') + 1, val.result.defaultValue.length);
                            if(this.treeSelectData.fromType === '字典项') {
                                this.queryAllTreeList(val.result.guid)
                            } else {
                                this.getTreeList(val.result.guid);
                            }
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                console.log('取消成功');
            }
        });
    }

    // 字典项保存
    itemSava() {
        if(this.isCancel) {
            if (!this.isEdit) { // 新增字典项
                const jsonOption = this.dictItemAdd;
                jsonOption.guidDict = this.treeSelectData.guid;
                this.utilityService.postData(appConfig.serverUrl  + appConfig.API.sysDictItems, jsonOption)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            // this.getData();
                            if(this.treeSelectData.fromType === '字典项') {
                                this.queryAllTreeList(this.dictInfo.guid)
                            } else {
                                this.getTreeList(this.dictInfo.guid);
                            }
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                            if(this.treeSelectData.fromType === '字典项') {
                                this.queryAllTreeList(this.dictInfo.guid)
                            } else {
                                this.getTreeList(this.dictInfo.guid);
                            }
                        }
                    );
            } else { // 修改业务字典项接口
                const jsonOption = this.dictItemAdd;
                jsonOption.guidDict = this.treeSelectData.guidParent;
                this.utilityService.putData( appConfig.serverUrl  + appConfig.API.sysDictItems, jsonOption)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            if(this.treeSelectData.fromType === '字典项') {
                                this.queryAllTreeList(this.dictInfo.guid)
                            } else {
                                this.getTreeList(this.dictInfo.guid);
                            }
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                            // this.getData();
                            if(this.treeSelectData.fromType === '字典项') {
                                this.queryAllTreeList(this.dictInfo.guid)
                            } else {
                                this.getTreeList(this.dictInfo.guid);
                            }
                        }
                    );
            }
            this.dictionaryItems = false; // 关闭弹窗
        }
    }

    // 树节点搜索框的内容
    searchVal($event) {
        let jsonObj = {
            guid: this.dictInfo.guid,
            dictName: $event
        }
        if(this.dictInfo.fromType === '字典项') { // 一次性给的所以单独写
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.sysDictsFilterTree, jsonObj)
                .subscribe(
                    (val) => {
                        if (val.code === '200' || val.code === 200) {
                            if (val.result.children !== undefined && val.result.children.length > 0) {
                                val.result.label = val.result.dictKey + ':' + val.result.dictName;
                                val.result.defaultValue = this.defaultValue;
                                val.result.expandedIcon = 'fa-folder-open';
                                val.result.collapsedIcon = 'fa-folder';
                                val.result.childDict = true; // 是业务字典
                                this.treedata = [val.result];
                                this.iteration(this.treedata); // 递归更改树节点信息
                            } else {
                                val.result.label = val.result.dictKey + ':' + val.result.dictName;
                                val.result.defaultValue = this.defaultValue;

                                val.result.expandedIcon = 'fa-folder-open';
                                val.result.collapsedIcon = 'fa-folder';
                                val.result.childDict = true; // 是业务字典
                                this.treedata = [val.result];
                            }
                            this.treeshow = true; // 显示树结构
                            this.treedata.forEach( node => {
                                this.expandRecursive(node, true);
                            });
                        }
                    },
                );
        } else {
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.sysDictsFilterTree, jsonObj)
                .subscribe(
                    (val) => {
                        if (val.result.dictName) {
                            val.result.label = val.result.dictKey + ':' + val.result.dictName;
                            val.result.defaultValue = this.defaultValue;
                            val.result.expandedIcon = 'fa-folder-open';
                            val.result.collapsedIcon = 'fa-folder';
                            val.result.childDict = true; // 是业务字典
                        }
                        if (val.result.children !== undefined && val.result.children.length > 0) {
                            for (let i = 0 ; i < val.result.children.length; i++) {
                                if (val.result.children[i].dictName) { // 子业务字典
                                    val.result.children[i].label = val.result.children[i].dictKey + ':' + val.result.children[i].dictName;
                                    val.result.children[i].expandedIcon = 'fa-folder-open';
                                    val.result.children[i].collapsedIcon = 'fa-folder';
                                    val.result.children[i].childDict = true;
                                    val.result.children[i].children = [{'label': ''}];
                                }
                                if (val.result.children[i].itemName) { // 字典项
                                    // 判断默认值
                                    if (val.result.children[i].itemValue === this.defaultValue) {
                                        val.result.children[i].icon = 'anticon anticon-tag';
                                    } else {
                                        val.result.children[i].icon = 'fa-file-word-o';
                                    }
                                    val.result.children[i].label = val.result.children[i].itemValue + '---' + val.result.children[i].itemName;
                                    val.result.children[i].childDict = false;
                                }
                            }
                        }
                        if(val.result.children.length === 0 ) {
                            this.nznot.create('error', '暂无搜索信息' , '暂无搜索信息');
                        }
                        const treeData = [];
                        treeData.push(val.result);
                        this.treedata  = treeData;
                        this.treeshow = true;
                        // 展开所有的
                        this.treedata.forEach( node => {
                            this.expandRecursive(node, true);
                        } );
                    },
                );
        }
    }



    // 展开所有树节点的方法
    private expandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if(node.children){
            node.children.forEach( childNode => {
                this.expandRecursive(childNode, isExpand);
            } );
        }
    }


    // switch开关
    switchchange(status) {
        this.isParent = status;
    }


    // 按钮取消方法
    dictCancel() {
        this.dictionaryItems = false;
        this.isCancel = false;
    }


    // 树节点三个按钮方法
    clickFunc($event) {
        if($event === 'reset') {
           //  应该判断，两种不同的重置方式
           this.queryAllTreeList(this.dictGuid);
            // this.getTreeList(this.dictInfo.guid)
        } else if($event === 'expand') { // 全部展开方法
            this.treedata.forEach( node => {
                this.expandRecursive(node, true);
            });
        }
    }

}
